import type { ContextMenuInstance, AddMenuProps, MeunItem } from '@/components/interfaceType'
import IconMenuDialog from './IconMenuDialog.vue'
import { render } from 'vue'

let currentInstance: ContextMenuInstance | null = null
let seed = 1
const editIconMenu = (resolve: (value: unknown | MeunItem) => void, reject: (reason?: any) => void, config: any) => {
  // 销毁之前的菜单
  if (currentInstance) {
    currentInstance.destroy()
  }
  currentInstance = null
  // 创建一个临时的 div，用于挂载菜单
  const container = document.createElement('div')
  let id = seed++
  // 获取 body 标签，用于挂载整个菜单
  const body = document.body
  // 传给 menu 组件的 props
  // let config:MeunItem = {
  //   name:"",
  //   id:0
  // }
  let dialogConfig: boolean = true
  const props: AddMenuProps = {
    config,
    dialogConfig,
    onClose: () => {
      if (currentInstance) {
        currentInstance.destroy()
        container.remove()
        reject()
      }
    },
    onSubmit: (data:MeunItem) => {
      if (currentInstance) {
        resolve(data)
        currentInstance.destroy()
        container.remove()
      }
    },
  }
  // 渲染虚拟节点
  const vNode = h(
    IconMenuDialog,
    props
  )

  // vNode 为需要渲染的虚拟节点，container 为渲染的容器
  render(vNode, container)

  body.appendChild(container)
  // 菜单实例
  const instance: ContextMenuInstance = {
    id,
    destroy: () => {
      currentInstance = null
      render(null, container)
    },
  }

  currentInstance = instance
  return instance
}

function editIconMenu2(config: any) {
  return new Promise((resolve: (value: unknown | MeunItem) => void, reject: (reason?: any) => void) => {
    editIconMenu(resolve, reject, config)
  })
}

export default editIconMenu2
